﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;

using MpSoft.Library.BUSS.Products;
using MpSoft.Library.DTO;
using MpSoft.Basic.Utils;
using MpSoft.Library.BUSS.Settings;

namespace MpSoft.Web.AdminCP.Controls.Product
{
    public partial class ProductEdit : System.Web.UI.UserControl
    {
        #region Var

        private int productID = -1;
        private bool showlanguage = false;

        #endregion

        #region Method

        #region language Default

        private void BindControl()
        {
            SetControl();
            if (productID > 0)
            {
                var obj = ProductBUSS.Product_ByID(productID);
                if (obj != null)
                {
                    ddlCategory.SelectVlaue = obj.CategoryID;
                    txtOrderSort.NumberIncremnet = obj.SortOrder;
                    chkIsActive.Checked = obj.IsActive;
                    chkIsHome.Checked = obj.IsHome;
                    chkIsHot.Checked = obj.IsHot;
                    chkIsExist.Checked = obj.IsExist;
                    chkIsPromotion.Checked = obj.IsPromotion;
                    chkIsVAT.Checked = obj.IsVAT;
                    chkIsSellGood.Checked = obj.IsSellGood;

                    contentLngDefault.Name = obj.ProductName;
                    contentLngDefault.Description = obj.Description;
                    contentLngDefault.Content = obj.Content;
                    txtProductCode.Text = obj.ProductCode;
                    txtPrice.Text = obj.Price == 0 ? "" : double.Parse(obj.Price.ToString()).ToString();
                    txtPriceNew.Text = obj.PriceNew == 0 ? "" : double.Parse(obj.PriceNew.ToString()).ToString();
                    //Attribute
                    if (ddlManufacturer.Items.FindByValue(obj.ManufacturerID.ToString()) != null)
                        ddlManufacturer.Items.FindByValue(obj.ManufacturerID.ToString()).Selected = true;   
                    //Images
                    if (obj.Images.Contains("@"))
                    {
                        var imgs = obj.Images.Split('@');
                        SelectImages.ShowImage = imgs[0];
                        SelectImages.Images = imgs[1];
                    }
                    else
                        SelectImages.Images = obj.Images;
                       
                    //SEO
                    contentLngDefault.MetaTitle = obj.MetaTitle;
                    contentLngDefault.MetaKeyWord = obj.MetaKeyword;
                    contentLngDefault.MetaDescription = obj.MetaDescription;
                    contentLngDefault.SeName = obj.SeName;
                }
            }
        }

        private void BindAttribute()
        {
            var list = AttributeBUSS.Attribute_Select(-1, 1, true);
            ddlAttribute.DataSource = list;
            ddlAttribute.DataTextField = "Name";
            ddlAttribute.DataValueField = "AttributeID";
            ddlAttribute.DataBind();
        }

        private void BindProductAttribute()
        {
            var list = AttributeValueBUSS.ProductAttribute_Select(productID, -1, 1);
            rpList.DataSource = list;
            rpList.DataBind();
        }

        private int Save()
        {

            Library.DTO.Product obj = null;
            if(productID>0)
                obj = ProductBUSS.Product_ByID(productID);
            if (obj == null)
                obj = new Library.DTO.Product();
            obj.CategoryID = ddlCategory.SelectVlaue;
            obj.SortOrder = txtOrderSort.NumberIncremnet;
            obj.IsActive = chkIsActive.Checked;
            obj.IsHome = chkIsHome.Checked;
            obj.IsHot = chkIsHot.Checked;
            obj.IsExist = chkIsExist.Checked;
            obj.IsPromotion = chkIsPromotion.Checked;
            obj.IsVAT = chkIsVAT.Checked;
            obj.IsSellGood = chkIsSellGood.Checked;

            obj.ProductCode = string.IsNullOrEmpty(txtProductCode.Text) ? null : txtProductCode.Text;
            obj.ProductName = contentLngDefault.Name;
            obj.Description = contentLngDefault.Description;
            obj.Content = string.IsNullOrEmpty(contentLngDefault.Content) ? null : contentLngDefault.Content;
            //giá
            double value = 0;
            double.TryParse(txtPrice.Text, out value);
            obj.Price = value;
            double.TryParse(txtPriceNew.Text, out value);
            obj.PriceNew = value;
            // Atribute
            int intValue = 0;
            int.TryParse(ddlManufacturer.SelectedValue, out intValue);
            obj.ManufacturerID = intValue;
            
            //Images
            obj.Images = !string.IsNullOrEmpty(SelectImages.ShowImage) ? SelectImages.ShowImage + "@" + SelectImages.Images : SelectImages.Images;
            //SEO
            obj.MetaTitle = string.IsNullOrEmpty(contentLngDefault.MetaTitle) ? obj.ProductName : contentLngDefault.MetaTitle;
            obj.MetaKeyword = contentLngDefault.MetaKeyWord;
            obj.MetaDescription = contentLngDefault.MetaDescription;
            obj.SeName = string.IsNullOrEmpty(contentLngDefault.SeName) ? CommonHelper.FillterChar(contentLngDefault.Name) : CommonHelper.FillterChar(contentLngDefault.SeName);
            obj.FormatUrl = SEOHelper.FormatUrl(ddlCategory.Category != null ? ddlCategory.Category.SeName : "san-pham", obj.SeName);

            if (obj.ProductID > 0)
            {
                SaveLanguage(obj.ProductID);
                return ProductBUSS.Product_Update(obj);
            }
            else
            {
                productID = ProductBUSS.Product_Add(obj);
                SaveLanguage(productID);
                return productID;
            }
        }

        private void Message(string message)
        {
            if (productID < 0)
                MpSoft.Basic.Utils.CommonHelper.ResetForm(this.Controls);
            ltlMessage.Text = "<p class='message-success'><i class='glyphicon-ok'></i> " + message + "</p>";
        }

        private void BindManufacturer()
        {
            if (ddlManufacturer.Items.Count < 1)
            {
                var list = ManufacturerBUSS.Manufacturer_Select(-1, false, 1);
                ddlManufacturer.DataTextField = "Name";
                ddlManufacturer.DataValueField = "ManufacturerID";
                ddlManufacturer.DataSource = list;
                ddlManufacturer.DataBind();
                ddlManufacturer.Items.Insert(0, new ListItem("--Chọn hãng sản xuất--", ""));
            }
        }

        // Thiết lập mặc định
        private void SetControl()
        {
            ddlCategory.DdlCategories.CssClass = "form-select";
            ddlCategory.DdlCategories.Attributes.Add("data-rule-required", "true");
            ddlCategory.DdlCategories.Attributes.Add("style", "width:auto;");
            BindManufacturer();
            BindAttribute();
            BindProductAttribute();
            showlanguage = true;
            ddlCategory.Module = "san-pham";
            contentLngDefault.NameNotNull = true;
            BindLanguage();
        }

        #endregion

        #region Language Orther

        protected string TabLanguage()
        {
            var list = LanguageBUSS.Language_Select(null);
            if (list != null)
            {
                StringBuilder sb = new StringBuilder();
                foreach (var obj in list)
                    sb.Append(" <option value='#" + obj.LanguageCode + "'>" + obj.LanguageTitle + "</option>");
                return sb.ToString();
            }
            return "";
        }

        private void BindLanguage()
        {
            listLanguage.DataSource = LanguageBUSS.Language_Select(null);
            listLanguage.DataBind();
        }
        /// <summary>
        /// Save Object Language by ID
        /// </summary>
        /// <param name="newsid"></param>
        private void SaveLanguage(int _itemID)
        {
            if (_itemID < 1) return;
            if (listLanguage.Items.Count < 1) return;
            foreach (RepeaterItem item in listLanguage.Items)
            {
                var ContentLanguage = item.FindControl("ContentLanguage") as Modules.ContentLanguage;
                if (ContentLanguage != null)
                {
                    if (string.IsNullOrEmpty(ContentLanguage.Language) || string.IsNullOrEmpty(ContentLanguage.Name))
                        continue;
                    var obj = ProductLanguageBUSS.ProductLanguage_ByID(_itemID, ContentLanguage.Language);
                    if (obj == null)
                        obj = new ProductLanguage();
                    obj.LanguageCode = ContentLanguage.Language;
                    obj.ProductID = _itemID;
                    obj.ProductName = ContentLanguage.Name;
                    obj.Description = ContentLanguage.Description;
                    obj.Content = ContentLanguage.Content;
                    obj.MetaTitle = string.IsNullOrEmpty(ContentLanguage.MetaTitle) ? obj.ProductName : ContentLanguage.MetaTitle;
                    obj.MetaKeyword = ContentLanguage.MetaKeyWord;
                    obj.MetaDescription = ContentLanguage.MetaDescription;
                    obj.SeName = string.IsNullOrEmpty(contentLngDefault.SeName) ? CommonHelper.FillterChar(obj.ProductName) : contentLngDefault.SeName;
                    obj.FormatUrl = SEOHelper.FormatUrl(ddlCategory.Category != null ? ddlCategory.Category.SeName : "tin-tuc", obj.SeName);
                    if (obj.PLID > 0)
                        ProductLanguageBUSS.ProductLanguage_Update(obj);
                    else
                        ProductLanguageBUSS.ProductLanguage_Add(obj);
                }
            }
        }

        #endregion

        #endregion

        #region Event

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.QueryString["itemid"] != null)
                int.TryParse(Request.QueryString["itemid"].ToString(), out productID);
            if (!IsPostBack)
                BindControl();
            
        }

        protected void cmdSave_Click(object sender, EventArgs e)
        {
            var _prodid = Save();
            if (_prodid > 0)
                Message("Cập nhật thành công!");
        }

        protected void cmdSaveExit_Click(object sender, EventArgs e)
        {
            var _prodid = Save();
            if (_prodid > 0)
                Response.Redirect("?mod=product");
            
        }

        protected void listLanguage_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            var ContentLanguage = e.Item.FindControl("ContentLanguage") as Modules.ContentLanguage;
            if (ContentLanguage != null)
            {
                var objLanguage = e.Item.DataItem as Language;
                ContentLanguage.Language = objLanguage.LanguageCode;
                var obj = ProductLanguageBUSS.ProductLanguage_ByID(productID, objLanguage.LanguageCode);
                if (obj != null)
                {
                    ContentLanguage.Name = obj.ProductName;
                    ContentLanguage.Description = obj.Description;
                    ContentLanguage.Content = obj.Content;
                    ContentLanguage.MetaTitle = obj.MetaTitle;
                    ContentLanguage.MetaKeyWord = obj.MetaKeyword;
                    ContentLanguage.MetaDescription = obj.MetaDescription;
                    ContentLanguage.SeName = obj.SeName;
                }
            }
        }

        #endregion

        #region Properties

        public int ProductID { get { return productID; } }
        public bool ShowLanguage { get { return showlanguage; } }

        #endregion
    }
}